package com.jarchie.htgl.activity;

import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TextView;

import com.coder.zzq.smartshow.toast.SmartToast;
import com.jarchie.htgl.R;
import com.jarchie.htgl.animation.ExpandableViewHoldersUtil;
import com.jarchie.htgl.base.BaseActivity;
import com.jarchie.htgl.base.BaseApp;
import com.jarchie.htgl.bean.ApproveListBean;
import com.jarchie.htgl.bean.ConDetailBean;
import com.jarchie.htgl.bean.ResultBean;
import com.jarchie.htgl.constants.ConfigConstant;
import com.jarchie.htgl.event.RefreshEvent;
import com.jarchie.htgl.network.Api;
import com.jarchie.htgl.utils.CommonUtils;
import com.jarchie.htgl.views.CommonDialog;
import com.jarchie.htgl.views.DialogLoader;
import com.jarchie.htgl.views.SpinnerPopWindow;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Jarchie on 2017\12\18.
 * 合同审批的详情页
 */

public class ApproveDetailActivity extends BaseActivity implements View.OnClickListener {
    private Toolbar mToolbar;
    private LinearLayout exceptionLayout,selectLayout,intentLayout;
    private TextView tipsMessage;
    private ImageView mImageView;
    private ScrollView mScrollView;
    //页面内部的显示文本的控件
    private TextView startTime, endTime, conName, conType, conNumber, Number, Jine, zhangqi, conContent,
            comName, depName, clientName, proNumber, proName, yewugk, saleto, saleStaff, note, backType;
    private TextView btnAgree, btnDisAgree; //按钮
    private RadioButton rbMaoyi, rbFeiMaoyi; //贸易/非贸易的单选框
    private EditText editShenpi;
    private SpinnerPopWindow<String> mBackSpinner; //回退类型的下拉框
    private List<String> mBackList = new ArrayList<>();
    private ConDetailBean.INFOBean bean;
    private ApproveListBean.INFOBean listBean;
    //弹出框
    private CommonDialog mCommonDialog;
    private TextView tvTips,btnConfirm, btnCancel;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_approve_detail;
    }

    @Override
    protected void initView() {
        mToolbar = obtainView(R.id.toolbar);
        exceptionLayout = obtainView(R.id.exception_layout);
        tipsMessage = obtainView(R.id.tv_exception);
        mScrollView = obtainView(R.id.mScrollView);
        startTime = obtainView(R.id.tv_start_time);
        endTime = obtainView(R.id.tv_end_time);
        conName = obtainView(R.id.tv_con_name);
        conType = obtainView(R.id.tv_con_type);
        conNumber = obtainView(R.id.tv_con_number);
        Number = obtainView(R.id.tv_number);
        Jine = obtainView(R.id.tv_jine);
        zhangqi = obtainView(R.id.tv_zhangqi);
        conContent = obtainView(R.id.tv_con_content);
        comName = obtainView(R.id.tv_com_name);
        depName = obtainView(R.id.tv_dep_name);
        clientName = obtainView(R.id.tv_client_name);
        proNumber = obtainView(R.id.tv_pro_number);
        proName = obtainView(R.id.tv_pro_name);
        yewugk = obtainView(R.id.tv_ywgk);
        saleto = obtainView(R.id.tv_saleto);
        saleStaff = obtainView(R.id.tv_sale_staff);
        note = obtainView(R.id.tv_note);
        btnAgree = obtainView(R.id.btn_agree);
        btnDisAgree = obtainView(R.id.btn_disagree);
        rbMaoyi = obtainView(R.id.maoyi_rb);
        rbFeiMaoyi = obtainView(R.id.feimaoyi_rb);
        backType = obtainView(R.id.tv_tuihui_type);
        editShenpi = obtainView(R.id.edit_spyj);
        mImageView = obtainView(R.id.select_img);
        intentLayout = obtainView(R.id.intent_layout);
        selectLayout = obtainView(R.id.select_layout);
        mBackSpinner = new SpinnerPopWindow<>(this, mBackList, backItemListener);
        mCommonDialog = new CommonDialog(this, R.layout.dialog_alert_layout);
        mCommonDialog.setCanceledOnTouchOutside(false);
        mCommonDialog.setCancelable(false);
        btnConfirm = mCommonDialog.findViewById(R.id.btn_confirm);
        btnCancel = mCommonDialog.findViewById(R.id.btn_cancel);
        tvTips = mCommonDialog.findViewById(R.id.dialog_tip);
    }

    @Override
    protected void setListener() {
        mToolbar.setOnClickListener(this);
        btnAgree.setOnClickListener(this);
        btnDisAgree.setOnClickListener(this);
        selectLayout.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
        mBackSpinner.setOnDismissListener(backDismissListener);
    }

    @Override
    protected void initData() {
        listBean = (ApproveListBean.INFOBean) getIntent().getSerializableExtra("detail");
        String intentState = getIntent().getStringExtra("page");
        addData();
        requestDetailData();
        if (intentState.equals(ConfigConstant.PAGE_INTENT_NO)){
            intentLayout.setVisibility(View.VISIBLE);
        }else if (intentState.equals(ConfigConstant.PAGE_INTENT_ALREADY)){
            intentLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar: //返回
                finish();
                break;
            case R.id.select_layout: //退回类型
                mBackSpinner.setWidth(selectLayout.getWidth());
                mBackSpinner.showAsDropDown(selectLayout,0,1);
                ExpandableViewHoldersUtil.rotateExpandIcon(mImageView, 0, 180);
                break;
            case R.id.btn_agree: //同意按钮
                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                tvTips.setText("确定要提交该审批信息吗？");
                mCommonDialog.setTag(ConfigConstant.STATE_AGREE);
                mCommonDialog.show();
                break;
            case R.id.btn_disagree: //不同意按钮
                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                tvTips.setText("确定要退回该合同吗？");
                mCommonDialog.setTag(ConfigConstant.STATE_DISAGREE);
                mCommonDialog.show();
                break;
            case R.id.btn_confirm: //确定按钮
                mCommonDialog.cancel();
                approveContract(mCommonDialog.getTag());
                break;
            case R.id.btn_cancel: //取消按钮
                mCommonDialog.cancel();
                break;
        }
    }

    //合同审批处理逻辑
    private void approveContract(String flag){
        if (flag.equals(ConfigConstant.STATE_AGREE)){ //同意
            editShenpi.setText("同意");
            backType.setClickable(false);
            requestApproveData(flag);
        }else if (flag.equals(ConfigConstant.STATE_DISAGREE)){ //不同意
            backType.setClickable(true);
            if (backType.getText().toString().equals(getString(R.string.tuihui_tips))){
                editShenpi.setText("");
                SmartToast.showInCenter(getString(R.string.tuihui_tips));
            }else if (editShenpi.getText().toString().length() == 0){
                SmartToast.showInCenter("请输入具体审批意见！");
            }else {
                requestApproveData(flag);
            }
        }
    }

    //POST提交合同审批接口数据
    private void requestApproveData(final String flag){
        Map<String,Object> map = new HashMap<>();
        map.put("htbh",bean.getHtbh());
        map.put("htgsmc",listBean.getGsmc());
        map.put("htbmmc",listBean.getBmmc());
        map.put("gsdm",listBean.getGsdm());
        map.put("jsdm", BaseApp.getInstance().getUserLogin().getINFO().get(0).getJsdm());
        if (flag.equals(ConfigConstant.STATE_AGREE)){
            map.put("sfty","Y");
            map.put("zflx","");
        }else if (flag.equals(ConfigConstant.STATE_DISAGREE)){
            map.put("sfty","N");
            map.put("zflx",backType.getText().toString());
        }
        map.put("spyj",editShenpi.getText().toString());
        map.put("spr",BaseApp.getInstance().getUserLogin().getINFO().get(0).getXm());
        Api.getInstance().requestConApprove(map).enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(@NonNull Call<ResultBean> call, @NonNull Response<ResultBean> response) {
                if (response.isSuccessful()){
                    if (response.body().getMSG().equals(ConfigConstant.SUCCESS)){
                        if (flag.equals(ConfigConstant.STATE_AGREE)){
                            SmartToast.showInCenter("审核成功");
                        }else if (flag.equals(ConfigConstant.STATE_DISAGREE)){
                            SmartToast.showInCenter("退回成功");
                        }
                        EventBus.getDefault().post(new RefreshEvent(ConfigConstant.PAGING_REFRESH));
                        finish();
                    }else if (response.body().getMSG().equals(ConfigConstant.ERROR)){
                        if (flag.equals(ConfigConstant.STATE_AGREE)){
                            SmartToast.showInCenter("审核失败");
                        }else if (flag.equals(ConfigConstant.STATE_DISAGREE)){
                            SmartToast.showInCenter("退回失败");
                        }
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<ResultBean> call, @NonNull Throwable t) {
                SmartToast.showInCenter(t.getMessage());
            }
        });
    }

    //设置数据
    private void setData(ConDetailBean.INFOBean bean) {
        startTime.setText(bean.getQsrq()); //开始时间
        endTime.setText(bean.getZzrq()); //结束时间
        conName.setText(bean.getHtmc()); //合同名称
        conType.setText(listBean.getLxmc()); //合同类型
        conNumber.setText(bean.getHtbh()); //合同编号
        Number.setText(bean.getSl()); //数量
        Jine.setText("¥" + bean.getJe()); //金额
        zhangqi.setText(bean.getZq()); //账期
        conContent.setText(bean.getHtnr()); //合同内容
        comName.setText(listBean.getGsmc()); //公司名称
        depName.setText(listBean.getBmmc()); //部门名称
        clientName.setText(bean.getKhmc()); //客户名称
        proNumber.setText(bean.getXmbh() == null ? "无" : bean.getXmbh().toString()); //项目编号
        proName.setText(bean.getXmmc() == null ? "无" : bean.getXmmc().toString()); //项目名称
        yewugk.setText(bean.getYwgk()); //业务归口
        saleto.setText(bean.getXsqx() == null ? "无" : bean.getXsqx().toString()); //销售去向
        saleStaff.setText(bean.getXsy() == null ? "无" : bean.getXsy()); //销售人员
        note.setText(bean.getBz()); //备注
    }

    //请求网络数据
    private void requestDetailData() {
        DialogLoader.show(this);
        if (listBean != null) {
            Api.getInstance().requestConDetailData(listBean.getHtbh()).enqueue(new Callback<ConDetailBean>() {
                @Override
                public void onResponse(@NonNull Call<ConDetailBean> call, @NonNull Response<ConDetailBean> response) {
                    DialogLoader.dismiss();
                    if (response.isSuccessful()) {
                        if (response.body().getMSG().equals(ConfigConstant.SUCCESS)) {
                            bean = response.body().getINFO();
                            if (bean != null) {
                                setData(bean);
                            } else {
                                exceptionLayout.setVisibility(View.VISIBLE);
                                tipsMessage.setText(getString(R.string.tips_no_data));
                            }
                        } else if (response.body().getMSG().equals(ConfigConstant.ERROR)) {
                            exceptionLayout.setVisibility(View.VISIBLE);
                            tipsMessage.setText(getString(R.string.tips_error_data));
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<ConDetailBean> call, @NonNull Throwable t) {
                    exceptionLayout.setVisibility(View.VISIBLE);
                    tipsMessage.setText(getString(R.string.tips_failure_data));
                }
            });
        } else {
            SmartToast.showInCenter("数据传递失败");
        }
    }

    //退回类型每一项点击事件
    private OnItemClickListener backItemListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            backType.setText(mBackList.get(position));
            mBackSpinner.dismiss();
        }
    };

    //退回类型取消监听
    private OnDismissListener backDismissListener = new OnDismissListener() {
        @Override
        public void onDismiss() {
            ExpandableViewHoldersUtil.rotateExpandIcon(mImageView, 180, 0);
            mBackSpinner.dismiss();
        }
    };

    //添加数据到集合中
    private void addData() {
        mBackList.add(getString(R.string.tuihui_content1));
        mBackList.add(getString(R.string.tuihui_content2));
        mBackList.add(getString(R.string.tuihui_content3));
    }

    //点击空白处隐藏软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN){
            View view = getCurrentFocus();
            if (CommonUtils.isHideInput(view,ev)){
                CommonUtils.hideSoftInput(this,view.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

}
